package cn.tedu.egvehicle1.base.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUESTS_RER_MINUTE = 3;
    private static final int WINDOW_SIZE_SECONDS = 60;

    private final ConcurrentHashMap<String,Integer> clientCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastResetTimes = new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String clientId = request.getRemoteAddr();

        LocalDateTime localDateTime = lastResetTimes.get(clientId);

        if(localDateTime == null || LocalDateTime.now().isAfter(localDateTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCounts.put(clientId,0);
            lastResetTimes.put(clientId,LocalDateTime.now());
        }

        Integer count = clientCounts.merge(clientId, 1, Integer::sum);

        if(count>MAX_REQUESTS_RER_MINUTE){
            throw new RuntimeException("访问过于频繁，请稍后再试");
        }
        return true;
    }
}
